/* eslint-disable no-undef */
import { defineConfig } from "vite";
import { resolve } from "path";
import vue from "@vitejs/plugin-vue";
import { setting } from "./src/config/setting";
import { svgBuilder } from "./src/plugin/svgBuilder";
import vueI18n from "@intlify/vite-plugin-vue-i18n";
import Components from "unplugin-vue-components/vite"; // 组件注册
import Icons from "unplugin-icons/vite"; // icon相关
import IconsResolver from "unplugin-icons/resolver"; // icon相关
import legacy from "@vitejs/plugin-legacy";

const {
  base,
  publicDir,
  outDir,
  assetsDir,
  sourcemap,
  cssCodeSplit,
  host,
  hmr,
  port,
  strictPort,
  open,
  cors,
  brotliSize,
  logLevel,
  drop_console,
  drop_debugger,
  chunkSizeWarningLimit,
} = setting;

const isDev = process.env.NODE_ENV === "development";
const loadI18n = isDev ? vueI18n({ include: resolve(__dirname, "./src/locales/**") }) : "";
export default defineConfig({
  root: process.cwd(),
  base,
  publicDir,
  logLevel,
  plugins: [
    vue(),
    loadI18n,
    legacy({
      polyfills: ["es.promise.finally", "es/map", "es/set"],
      modernPolyfills: ["es.promise.finally"],
    }),
    Components({
      resolvers: [
        // 自动注册图标组件
        IconsResolver({
          enabledCollections: ["ep"], // 重点
        }),
      ],
    }),
    Icons({
      autoInstall: true,
    }),
    svgBuilder("./src/icons/svg/"),
  ],

  server: {
    host,
    port,
    cors,
    strictPort,
    open,
    hmr, // 热刷新
    fs: {
      strict: false,
    },
    proxy: {
      "/fun-switch": {
        target: "localhost:10000", // 代理地址 http://xxx.xxx.xxx.xxx:8000
        changeOrigin: true,
        secure: false,
        rewrite: (path) => path.replace(`/fun-switch`, ""),
      },
    },
  },

  resolve: {
    // 设置别名
    alias: {
      views: resolve(__dirname, "src/views"),
      styles: resolve(__dirname, "src/styles"),
      "@": resolve(__dirname, "src"),
    },
  },

  css: {
    preprocessorOptions: {
      // 引入公用的样式
      scss: {
        additionalData: `@use "@/styles/index.scss" as *; @use "@/styles/element/index.scss" as *;`,
        charset: false,
      },
    },
    postcss: {
      plugins: [
        {
          postcssPlugin: "internal:charset-removal",
          AtRule: {
            charset: (atRule) => {
              if (atRule.name === "charset") {
                atRule.remove();
              }
            },
          },
        },
      ],
    },
  },

  corePlugins: {
    preflight: false,
  },

  build: {
    target: "es2015",
    outDir,
    assetsDir,
    sourcemap,
    cssCodeSplit,
    brotliSize,
    terserOptions: {
      compress: {
        keep_infinity: true,
        drop_console,
        drop_debugger,
      },
    },
    chunkSizeWarningLimit,
  },
});
